<?php

require_once 'dbutils.php';
require_once 'RestUtils.php';
require_once 'Base.php';

class SubscribeJourney extends Base
{

    function POST($matches)
    {
        $req = RestUtils::processRequest('POST');
        $req_vars = $req->getRequestVars();
        $db_vars = dbutils::translate_rest_params($req_vars);
        $res = $this->insertSubscription($db_vars);
        if ($res['code'] == 0)
            RestUtils::sendResponse(200);
        else
            RestUtils::sendResponse(404, dbutils::error_to_json($res['code'], $res['message']), 'application/json');
    }

    function DELETE($matches)
    {
        $req = RestUtils::processRequest('DELETE');
        $req_vars = $req->getRequestVars();
        $db_vars = dbutils::translate_rest_params($req_vars);
        $res = $this->deleteSubscription($db_vars);
        if ($res['code'] == 0)
            RestUtils::sendResponse(200);
        else
            RestUtils::sendResponse(404, dbutils::error_to_json($res['code'], $res['message']), 'application/json');
    }

    private function insertSubscription($values)
    {
        $code = 0;
        $msg = '';
        $result = null;
        try {
            if (!$values)
                return array('code' => -1, 'message' => 'required request parameters not found', 'result' => null);

            if (!array_key_exists('id_user', $values)
                || !array_key_exists('id_journey', $values)
            )
                return array('code' => -1, 'message' => 'required request parameters not found', 'result' => null);

            $db_handle = @pg_pconnect(dbutils::$conn_string);

            $res = @pg_query($db_handle, "SELECT j.status, uj.id_user
                                            FROM journeys j, user_journeys uj
                                            WHERE j.id = {$values['id_journey']}
                                            AND uj.fl_owner = '1'
                                            AND j.id = uj.id_journey");
            if ($res && @pg_num_rows($res) > 0) {
                $row = @pg_fetch_array($res, 0);
                if (strcasecmp($row['status'], 'CLOSE') != 0) {

                    $id_recipient = $row['id_user'];

                    $res = @pg_query($db_handle, "SELECT nextval('messages_id_seq') as key");
                    if ($res) {
                        $row = @pg_fetch_array($res, 0);
                        $id_message = $row['key'];
                    }
                    if ($id_message) {
                        $insert = "INSERT INTO user_journeys (id_user, id_journey, fl_owner)
                                   VALUES ({$values['id_user']}, {$values['id_journey']}, '0');";

                        $insert .= "INSERT INTO messages (id, title, body,
                                            datetime, id_journey,
                                            id_sender, id_recipient)
                                    VALUES ({$id_message}, 'NEW SUBSCRIPTION',
                                            'NEW SUBSCRIPTION', LOCALTIMESTAMP(0),
                                            {$values['id_journey']}, {$values['id_user']},
                                            {$id_recipient});";

                        $result = @pg_query($db_handle, $insert);
                        if (!$result) {
                            $code = -1;
                            $msg = 'inserting records not possible ' . @pg_last_error($db_handle);
                        }
                    } else {
                        $code = -1;
                        $msg = 'error generating idMessage ' . @pg_last_error($db_handle);
                    }
                } else {
                    $code = -2;
                    $msg = 'the journey is close';
                }
            } else {
                $code = -2;
                $msg = 'the journey is close';
            }
            @pg_close($db_handle);

        } catch (Exception $e) {
            $code = $e->getCode();
            $msg = $e->getMessage();
        }

        return array('code' => $code, 'message' => $msg, 'result' => $result);
    }

    private function deleteSubscription($values)
    {
        $code = 0;
        $msg = '';
        $result = null;
        try {
            if (!$values)
                return array('code' => -1, 'message' => 'required request parameters not found', 'result' => null);

            if (!array_key_exists('id_user', $values) || !array_key_exists('id_journey', $values))
                return array('code' => -1, 'message' => 'required request parameters not found', 'result' => null);

            $db_handle = @pg_pconnect(dbutils::$conn_string);

            $res = @pg_query($db_handle, "SELECT uj.id_user
                                            FROM journeys j, user_journeys uj
                                            WHERE j.id = {$values['id_journey']}
                                            AND uj.fl_owner = '1'
                                            AND j.id = uj.id_journey");
            if ($res && @pg_num_rows($res) > 0) {

                $row = @pg_fetch_array($res, 0);
                $id_recipient = $row['id_user'];

                $res = @pg_query($db_handle, "SELECT nextval('messages_id_seq') as key");
                if ($res) {
                    $row = @pg_fetch_array($res, 0);
                    $id_message = $row['key'];
                }
                if ($id_message) {

                    $delete = "DELETE FROM messages
                                WHERE (id_sender = {$values['id_user']}
                                   OR id_recipient = {$values['id_user']})
                                  AND id_journey = {$values['id_journey']};";

                    $delete .= "DELETE FROM user_journeys
                                WHERE id_user = {$values['id_user']}
                                  AND id_journey = {$values['id_journey']};";

                    $delete .= "INSERT INTO messages (id, title, body,
                                            datetime, id_journey,
                                            id_sender, id_recipient)
                                    VALUES ({$id_message}, 'DELETE SUBSCRIPTION',
                                            'DELETE SUBSCRIPTION', LOCALTIMESTAMP(0),
                                            {$values['id_journey']}, {$values['id_user']},
                                            {$id_recipient});";

                    $result = @pg_query($db_handle, $delete);
                    if (!$result) {
                        $code = -1;
                        $msg = 'deleting records not possible ' . @pg_last_error($db_handle);
                    }
                } else {
                    $code = -1;
                    $msg = 'error generating idMessage ' . @pg_last_error($db_handle);
                }
            } else {
                $code = -2;
                $msg = 'the journey is close';
            }
            @pg_close($db_handle);

        } catch (Exception $e) {
            $code = $e->getCode();
            $msg = $e->getMessage();
        }

        return array('code' => $code, 'message' => $msg, 'result' => $result);
    }
}

?>